package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.IStaticHtmlService;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Service
public class StaticHtmlServiceImpl implements IStaticHtmlService {

    @Autowired
    @Lazy
    private IApArticleService articleService;

    @Autowired
    private Configuration configuration;

    @Autowired
    private MinIOService minIOService;

    @Override
    @Async
    public void createStaticHtml(ApArticle apArticle, String content) {
        String url;
        // 通过模版引擎得到模版,默认从classpath:获取模板
        try {
            Template template = configuration.getTemplate("article.ftl");
            Map<String,Object> data = new HashMap<>();
            //content是内容的字符串,包含多个content的集合,而这里需要的是集合对象,所以通过JSON.parseArray转换
            data.put("content", JSON.parseArray(content));
            //合并模版和数据,object即数据
            Writer out = new StringWriter();
            template.process(data,out);
            //将流转换成字符串,再获取字节数组
            InputStream inputStream = new ByteArrayInputStream(out.toString().getBytes());
            String name = apArticle.getId() + ".html";
            url = minIOService.upload(name, inputStream, "text/html");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        apArticle.setStaticUrl(url);
        articleService.updateById(apArticle);
    }
}
